package com.mg.plugin.drought.common;

import com.mg.model.Model;
import com.mg.plugin.drought.entity.StationData;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CropWaterDeficitCalculator {
    /**
     * 计算CWDIa
     *
     * @param stationData    实况值
     * @param oldStationData 常年值
     * @param model          模型
     * @return
     */
    public static double calcCWDIa(List<StationData> stationData, List<StationData> oldStationData, Model model) throws ParseException {
        double newCWDI = calcCWDI(stationData, model);
        double oldCWDI = calcCWDI(oldStationData, model);
        if (oldCWDI <= 0) {
            return newCWDI;
        }
        return (newCWDI - oldCWDI) / (100 - oldCWDI) * 100;
    }

    private static double calcCWDI(List<StationData> stationDataList, Model model) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int day = 400;
        Calendar calendar = Calendar.getInstance();
        for (StationData stationData : stationDataList) {
            Date date = sdf.parse(stationData.getDate());
            calendar.setTime(date);
            stationData.setDay(calendar.get(Calendar.DAY_OF_YEAR));
            if (day > stationData.getDay()) {
                day = stationData.getDay();
            }
        }
        double[] cwdi = new double[5];
        for (int i = 0; i < 5; i++) {
            List<StationData> calcData = getCalcStationData(stationDataList, day + i * 10 + 10);
            cwdi[i] = PenmamCalculator.caleCWDI(calcData,calendar,sdf,model);
        }
        return 0.1 * cwdi[0] + 0.15 * cwdi[1] + 0.2 * cwdi[2] + 0.25 * cwdi[3] + 0.3 * cwdi[4];
    }

    private static List<StationData> getCalcStationData(List<StationData> stationDataList, int i) {
        List<StationData> calcData = new ArrayList<StationData>();
        for (StationData stationData : stationDataList) {
            if (i > stationData.getDay()) {
                calcData.add(stationData);
            }
        }
        return calcData.size() > 0 ? calcData : null;
    }
}
